import 'package:flutter/material.dart';

import 'package:top_foundation/component/window/window.dart';
import 'package:whale/helper/utils/util.dart';
import 'package:whale/pages/im/component/im_input_voice/widgets/tip.dart';

import '../../../../helper/utils/ifly/record.dart';
import '../im_input/controller.dart';
import 'index.dart';

class ImInputVoiceController extends GetxController {
  ImInputVoiceController();

  final inputController = Get.find<ImInputController>();

  final state = ImInputVoiceState();

  void onLongPressStart(LongPressStartDetails details) {
    getDy();
    state.time = DateTime.now();
    // state.record.start();
    IWindow.show(
      IMRecordTipWidget(),
      name: 'record',
    );
  }

  void onLongPressEnd(LongPressEndDetails details) async {
    locationEvent(details.globalPosition);
    IWindow.dismiss(name: 'record');
    // var result = await state.record.stop();

    state.duration = DateTime.now().difference(state.time).inSeconds;
    if (state.duration < 1) {
      Hud.toast('录音时间太短');
      return;
    }
    inputController.actionSendVoice(state.duration);
  }

  void onLongPressMoved(LongPressMoveUpdateDetails details) {
    getDy();
    locationEvent(details.globalPosition);
  }

  void onTapCancel() {
    cancelEvent();
  }

  void locationEvent(Offset location) {
    if (state.dy == null || state.dy == 0) {
      return;
    }
    var dy = location.dy - Get.mediaQuery.viewPadding.bottom;

    var isOutEffect = dy < state.dy!;
    if (state.isOutEffect != isOutEffect) {
      state.isOutEffect = isOutEffect;
      if (state.isOutEffect) {
        outBoundsEvent();
      } else {
        inBoundsEvent();
      }
      update();
    }
  }

  void outBoundsEvent() {}
  void inBoundsEvent() {}

  void cancelEvent() {
    // state.record.cancel();
  }

  void getDy() {
    if (state.effectKey.currentContext == null) {
      return;
    }
    if (state.dy == null || state.dy == 0) {
      var box = state.effectKey.currentContext!.findRenderObject() as RenderBox;
      state.dy = box.globalToLocal(Offset.zero).dy.abs() - 10.r;
    }
  }

  void recordStart() {
    state.record.start();
  }

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
    state.key = GlobalKey(debugLabel: 'voice');
    state.effectKey = GlobalKey(debugLabel: 'effect');
    state.record = RecordMan();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
    state.record.stop();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
    state.record.dispose();
  }
}
